<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #box {
      width: 300px;
      height: 300px;
      background-color: #ccc;
      position: relative;

    }
  </style>
</head>

<body>
  <div id="box" style="left: 0px; top: 0px;"></div>
</body>
<script>
  var box = document.getElementById("box")
  document.onkeydown = function (event) {
    switch (event.keyCode) {
      case 38:
        var top = box.style.top
        var x = parseInt(top)
        var result = x - 20
        box.style.top = result + "px"
        console.log("上")
        break
      case 39:
        //找到当前元素的left值
        var left = box.style.left
        var x = parseInt(left)
        var result = x + 20
        box.style.left = result + "px"
        console.log("右")
        break
      case 37:
        var left = parseInt(box.style.left)
        box.style.left = left - 20 + "px"
        console.log("左")
        break
      case 40:
        var top = parseInt(box.style.top)
        box.style.top = top + 20 + "px"
        console.log("下")
        break
      default: console.log("什么都不是")
        break
    }
  }
</script>

</html>